<template>
  <div class="user-container">
    <!--    查询表单-->
    <Search ref="search" :SearchConfig="SearchConfig" :searchData="searchData">
      <template #buttons>
        <ButtonGroup :ButtonConfig="ButtonConfig" :select-row="selectedRow"
                     @reset="reset" @query="query" @openDialog="openDialog" @delete="del"/>
      </template>
    </Search>
    <!--    数据网格-->
    <div class="data-grid">
      <el-table
          :data="gridData"
          @expand-change="handleExpandChange"
          :highlight-current-row="true"
          row-key="userId"
          :expand-row-keys="expandRowKeys"
          border
          @row-click="rowClick"
          height="520px"
          style="width: 100%">
        <el-table-column v-has-permission="['system:user:update']" type="expand" label="分配角色" width="70">
          <template slot-scope="props">
            <div class="role-container" v-if="props.row.username === 'admin'">
              <el-tag>
                {{ '系统管理员拥有最高权限，无需配置' }}
              </el-tag>
            </div>
            <div class="role-container" v-if="props.row.username !== 'admin'">
              <el-tag
                  v-for="role in props.row.roles"
                  :key="role.roleId"
                  style="margin-right: 4px"
                  closable
                  @close="handleTagClose(role.roleId,props.row.userId,props.row.roles)"
              >
                {{ role.roleName }}
              </el-tag>
              <el-popover
                  placement="right"
                  width="400"
                  trigger="click">
                <span style="margin: 0 4px;">添加角色</span>
                <el-select v-model="selectRoles" multiple filterable placeholder="请选择" style="width: 280px;">
                  <el-option
                      v-for="role in roleOptions"
                      :key="role.roleId"
                      :label="role.roleName"
                      :value="role.roleId">
                  </el-option>
                </el-select>
                <el-button type="success" icon="el-icon-check" circle style="margin-left: 10px;" @click="dispatchRoles(props.row)"></el-button>
                <el-tooltip class="item" slot="reference" effect="dark" content="添加角色" placement="top-end">
                  <el-button class="add-role-btn"  icon="el-icon-more"></el-button>
                </el-tooltip>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            type="index"
            fixed
            label="序号"
            width="50">
        </el-table-column>
        <el-table-column
            width="70"
            label="头像">
          <template slot-scope="scope">
            <el-avatar shape="square" :size="50" :src="scope.row.img"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column
            prop="userCode"
            label="用户编号"
            width="80">
        </el-table-column>
        <el-table-column
            prop="username"
            fixed
            label="账号"
            width="120">
        </el-table-column>
        <el-table-column
            prop="nameZh"
            label="用户名">
        </el-table-column>
        <el-table-column
            width="80"
            label="性别">
          <template slot-scope="scope">
            {{ scope.row.sex | getDictLabel(dicts['common_sex']) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="phone"
            width="100"
            label="手机号">
        </el-table-column>
        <el-table-column
            width="90"
            label="是否管理员">
          <template slot-scope="scope">
            {{ scope.row.isAdmin | getDictLabel(dicts['is_admin']) }}
          </template>
        </el-table-column>
        <el-table-column
            label="是否启用">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                @change="changeStatus(scope.row.userId)"
                inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createUserId"
            label="创建者">
        </el-table-column>
        <el-table-column
            prop="createTime"
            width="130"
            label="创建时间">
        </el-table-column>
        <el-table-column
            prop="updateTime"
            width="130"
            label="更新时间">
        </el-table-column>
        <el-table-column
            prop="remark"
            width="180"
            label="备注">
        </el-table-column>
      </el-table>
    </div>
    <!--    分页工具-->
    <page-comp :pageOptions="pageOptions"/>

    <add-or-update-dialog @close="closeDialog" @submit="submit" :options="dialogOptions">
      <template slot="form">
        <Form ref="form" :form-config="FormConfig" :form-data="FormData"></Form>
      </template>
    </add-or-update-dialog>
  </div>
</template>

<script>
import PageComp from '@/components/pagination'
import Search from '@/components/search/index'
import ButtonGroup from '@/components/ButtonGroup'
import {list, listNoHavRoleForUser, changeStatus, dispatchRole,add,update,deleteUser,deleteRole} from "@/api/sysuserApi";
import {SearchConfig,ButtonConfig,FormConfig,FormData,init} from "@/views/auth/user.config";
import AddOrUpdateDialog from '@/components/AddOrUpdateDialog'
import Form from '@/components/Form'

export default {
  name: 'User',
  components: {PageComp, Search,ButtonGroup,AddOrUpdateDialog,Form},
  dicts: ['common_sex','is_admin'],
  data() {
    return {
      pageOptions: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pagesizes: [10, 20, 30, 40],
        sizeChangeCallback(pageSize) {
          this.pageSize = pageSize
        },
        currentChangeCallback(currPage) {
          this.currentPage = currPage
        }
      },
      gridData: [],
      searchData: {
        username: ''
      },
      SearchConfig,
      ButtonConfig,
      FormConfig,
      FormData,
      roleOptions: [],
      selectRoles: [],
      expandRowKeys: [],
      dialogOptions: {
        title: '',
        isVisitable: false,
        width: '30%',
        type: null
      },
      selectedRow: null
    }
  },
  watch: {
    'pageOptions.currentPage': function (ne,old) {
        this.query()
    },
    'pageOptions.pageSize': function (ne,old){
      this.query()
    }
  },
  methods: {
    query() {
      list(this.searchData.username,this.pageOptions.currentPage,this.pageOptions.pageSize).then(success => {
        this.gridData = success.data
        this.pageOptions.total = success.total
        this.selectedRow = null
      })
    },
    openDialog(val) {
      if (val === '1') {
        this.dialogOptions.title = '添加'
        this.dialogOptions.type = 1
      } else {
        this.dialogOptions.title = '编辑'
        this.dialogOptions.type = 0
        this.copyField(this.selectedRow,this.FormData)
        // 解决select回显显示源码数据问题（原因： options的value类型和回显的数据类型不一致导致）
        this.FormData.sex = this.selectedRow.sex + ''
      }
      this.dialogOptions.isVisitable = true
    },
    reset() {
      this.$refs.search.resetFields()
    },
    dispatchRoles(row) {
      dispatchRole(row.userId,this.selectRoles).then(success => {
          this.query()
          this.expandRowKeys.push(row.userId)
          this.selectRoles = []
          listNoHavRoleForUser(row.userId).then(res => {
            this.roleOptions = res;
          })
      })
    },
    changeStatus(userId) {
      changeStatus(userId).then(success => {
        this.query()
      })
    },
    async handleExpandChange(row, expandRows) {
      // 设置同时只能展开一行，否则roleOptions就无法复用
      if (expandRows.length) {
        this.expandRowKeys = []
        this.expandRowKeys.push(row.userId)
      }
      const res = await listNoHavRoleForUser(row.userId)
      this.roleOptions = []
      this.roleOptions = res
    },
    closeDialog() {
      if (this.dialogOptions.type === 0 || this.dialogOptions.type === 1) {
        this.query()
      } else {

      }
      this.dialogOptions.isVisitable = false
      this.$refs.form.resetFormData()
    },
    submit() {
      this.$refs.form.validate(item => {
        if (this.dialogOptions.type === 1) {
          // 添加
          add(this.FormData).then(res => {
            this.closeDialog()
          })
        } else if(this.dialogOptions.type === 0) {
          // 编辑
          update(this.FormData).then(res => {
            this.closeDialog()
          })
        } else {
          // ...
        }
      })
    },
    rowClick(row,column,event) {
      this.selectedRow = row
    },
    del(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = []
        ids.push(row.userId)
        deleteUser(ids).then(success => {
          this.query()
          this.selectedRow = null
        })
      }).catch(() => {
        return
      });
    },
    handleTagClose(roleId,userId,roles) {
      this.$confirm('确认删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(userId,roleId).then(success => {
          roles.splice(roles.indexOf(roleId),1)
        })
      }).catch(() => {
        return
      });
    }
  },
  mounted() {
    list().then(success => {
      if (success) {
        this.gridData = success.data
        this.pageOptions.total = success.total
      }
    })

    setTimeout(() => {
      init(this.dicts)
    },800)
  }
}
</script>

<style scoped>
.user-container {
  position: relative;
  height: calc(100% - 31px);
}

.user-container > .data-grid {
  box-sizing: border-box;
  padding: 0 20px 10px 20px;
}

.data-grid .role-container {
  margin-left: 200px;
}

.role-container .add-role-btn {
  font-size: 18px;
  outline: none;
  border: none;
  margin-left: 4px;
}

.role-container .add-role-btn:hover {
  outline: none;
  border: none;
  background-color: white;
}

.role-container .add-role-btn:focus {
  outline: none;
  border: none;
  background-color: white;
}
</style>